/**
* @description: 931. 下降路径最小和
* @author hewei
* @date 2022/9/20 15:57
* @version 1.0
*/

public class MinFallingPathSum {

    public int minFallingPathSum(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            dp[0][i] = matrix[0][i];
            if (m == 1) ans = Math.min(ans, dp[0][1]);
        }
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (j == 0) {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j + 1]) + matrix[i][j];
                } else if (j == n - 1) {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + matrix[i][j];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i - 1][j - 1]), dp[i - 1][j + 1]) + matrix[i][j];
                }
                if (i == m - 1) ans = Math.min(ans, dp[i][j]);
            }
        }
        return ans;
    }
}
